from AdminApiRunner.app import db #db是在app/__init__.py生成的关联后的SQLAlchemy实例
# import core.Utils
from sqlalchemy.ext.declarative import declarative_base
from flask_jsontools import JsonSerializableBase
from sqlalchemy import Column, Float, Integer, String, DateTime, DATETIME, Boolean, ForeignKey, SmallInteger, Text, Numeric


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(320), unique=False)
    password = db.Column(db.String(32), nullable=False)
    login_time = db.Column(db.Integer)

    def __repr__(self):
        def convert_datetime(value):
            if value:
                return value.strftime("%Y-%m-%d %H:%M:%S")
            else:
                return ""

        for col in self.__table__.columns:
            if isinstance(col.type, DateTime):
                value = convert_datetime(getattr(self, col.name))
            elif isinstance(col.type, Numeric):
                value = float(getattr(self, col.name))
            else:
                value = getattr(self, col.name)
            yield (col.name, value)

    @staticmethod
    def check_password(self,password1,password2):
        from AdminApiRunner.core.Utils import PasswdUtil
        return PasswdUtil.md5(password2) == password1


class Admin(db.Model):
    __tablename__ = 'admins'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(320), unique=False)
    password = db.Column(db.String(32), nullable=False)

    def __repr__(self):
        def convert_datetime(value):
            if value:
                return value.strftime("%Y-%m-%d %H:%M:%S")
            else:
                return ""

        for col in self.__table__.columns:
            if isinstance(col.type, DateTime):
                value = convert_datetime(getattr(self, col.name))
            elif isinstance(col.type, Numeric):
                value = float(getattr(self, col.name))
            else:
                value = getattr(self, col.name)
            yield (col.name, value)